package com.example.springbootredis.controller;

import com.example.springbootredis.entiy.News;
import com.example.springbootredis.service.NewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {

    private final NewsService newsService;

    //添加文档
    @PostMapping
    public ResponseEntity<News> add(@RequestBody News news) {
        return ResponseEntity.ok(newsService.save(news));
    }

    //根据id查询
    @GetMapping("/{id}")
    public ResponseEntity<News> getById(@PathVariable String id) {
        Optional<News> news = newsService.findById(id);
        return news.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    // 根据id删除
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteById(@PathVariable String id) {
        if (newsService.findById(id).isPresent()) {
            newsService.deleteById(id);
            return ResponseEntity.ok("删除成功");
        } else {
            return ResponseEntity.badRequest().body("文档不存在");
        }
    }

    //搜索功能
    @GetMapping("/search")
    public ResponseEntity<List<News>> search(@RequestParam(required = false) String keyword) {
        List<News> result;
        if (keyword == null || keyword.trim().isEmpty()) {
            //关键字空
            result = (List<News>) newsService.findAll();
        } else {

            result = newsService.search(keyword);

        }
        // 倒序
        result.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        result.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        return ResponseEntity.ok(result);
    }
}